package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppActSelfCarDetailBinding;
import com.sgb.kjwl.model.entity.MyCarInfoEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.adapter.self.logistics.SelfCarDetailAdapter;
import com.sgb.kjwl.viewmodel.transport.SelfCarDetailViewModel;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2021/10/9 09:59
 * @Description: 自营车辆详情页
 */
public class SelfCarDetailActivity extends BaseActivity<SelfCarDetailViewModel, AppActSelfCarDetailBinding> {
    //车辆no
    private long mNo;
    //车货信息
    private List<SingleItemEntity> mInfoList;
    private SelfCarDetailAdapter mInfoAdapter;
    //实体类
    private MyCarInfoEntity mEntity;
    //图片列表
    private final List<String> mImageUrls = new ArrayList<>();

    public static void start(Context context, long no) {
        Intent intent = new Intent(context, SelfCarDetailActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(RouterKey.NO, no);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.app_act_self_car_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SelfCarDetailViewModel.class);
    }

    @Override
    protected void init() {
        mBinding.include.titleView.setText("车辆审核详情");
        initRecycler();
        initEvent();
        initData();
    }

    private void initRecycler() {
        //车货信息
        mInfoList = new ArrayList<>();
        mInfoAdapter = new SelfCarDetailAdapter(mInfoList);
        mBinding.rvVaInfo.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .showLastDivider()
                .build()
                .addTo(mBinding.rvVaInfo);
        mBinding.rvVaInfo.setAdapter(mInfoAdapter);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        mBinding.include.ivBack.setOnClickListener(this);
        //
        mViewModel.ldEntity.observe(this, this::syncCarInfo);
        mViewModel.ldCheckOrder.observe(this, haveOrder -> {
            if (haveOrder) {
                showUnbindErrorDialog();
                return;
            }
            showUnbindDialog();
        });
    }

    private void initData() {
        mNo = getIntent().getLongExtra(RouterKey.NO, 0);
        mViewModel.getVehicleDetail(mNo);
        //团队车辆无车队
        if (UserOperating.getInstance().isTeam()) {
            mBinding.tvVaBindDriverTeamTip.setVisibility(View.GONE);
            mBinding.tvVaBindDriverTeam.setVisibility(View.GONE);
        } else if (UserOperating.getInstance().isCompany()) {
            mBinding.tvVaBindDriverTeamTip.setVisibility(View.VISIBLE);
            mBinding.tvVaBindDriverTeam.setVisibility(View.VISIBLE);
        }
    }

    private void syncCarInfo(MyCarInfoEntity entity) {
        try {
            mEntity = entity;
            mImageUrls.clear();
            if (entity == null) {
                return;
            }
            mBinding.scrollVa.setVisibility(View.VISIBLE);
            //审核状态
            if (entity.getStatus() == 1 && entity.getState() == 0) {
                mBinding.tvVaStatus.setText("已下架");
                mBinding.tvVaStatus.setTextColor(Color.parseColor("#666666"));
                mBinding.tvVaStatusTip.setVisibility(View.VISIBLE);
                mBinding.tvVaStatusTip.setTextColor(Color.parseColor("#FFC000"));
                mBinding.tvVaStatusTip.setText(DefaultUtil.getString(entity.getRemark()));
                mBinding.tvVaDrivingEdit.setVisibility(View.VISIBLE);
            } else {
                switch (entity.getStatus()) {
                    case 0:
                        mBinding.tvVaStatus.setText("审核中");
                        mBinding.tvVaStatus.setTextColor(Color.parseColor("#FFC000"));
                        mBinding.tvVaStatusTip.setVisibility(View.VISIBLE);
                        mBinding.tvVaStatusTip.setTextColor(Color.parseColor("#666666"));
                        mBinding.tvVaStatusTip.setText("请耐心等待，车辆正在审核中");
                        //审核中不可编辑车辆信息
                        mBinding.tvVaDrivingEdit.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        mBinding.tvVaStatus.setText("审核通过");
                        mBinding.tvVaStatus.setTextColor(Color.parseColor("#06C764"));
                        mBinding.tvVaStatusTip.setVisibility(View.GONE);
                        mBinding.tvVaDrivingEdit.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        mBinding.tvVaStatus.setText("审核不通过");
                        mBinding.tvVaStatus.setTextColor(Color.parseColor("#EA4237"));
                        mBinding.tvVaStatusTip.setVisibility(View.VISIBLE);
                        mBinding.tvVaStatusTip.setTextColor(Color.parseColor("#FFC000"));
                        mBinding.tvVaStatusTip.setText(DefaultUtil.getString(entity.getRemark()));
                        mBinding.tvVaDrivingEdit.setVisibility(View.VISIBLE);
                        break;
                }
            }
            //行驶证信息
            mBinding.tvVaCarNumber.setText(DefaultUtil.getString(entity.getCarNumber()));
            loadImage(mBinding.ivVaMain, entity.getVehicleLicense());
            loadImage(mBinding.ivVaSub, entity.getDrivingLicensePage());
            loadImage(mBinding.ivVaActual, entity.getCarImage());
            //添加展示图片
            mImageUrls.add(DefaultUtil.getString(entity.getVehicleLicense()));
            mImageUrls.add(DefaultUtil.getString(entity.getDrivingLicensePage()));
            mImageUrls.add(DefaultUtil.getString(entity.getCarImage()));
            //车辆基本信息
            if (entity.getIsComplete() == 1) {
                mBinding.groupVaInfo.setVisibility(View.VISIBLE);
                mBinding.llVaFixInfo.setVisibility(View.GONE);
                mViewModel.syncCarInfo(mInfoList, entity);
                mInfoAdapter.notifyDataSetChanged();
            } else {
                mBinding.groupVaInfo.setVisibility(View.GONE);
                mBinding.llVaFixInfo.setVisibility(View.VISIBLE);
            }
            //车辆绑定司机
            mBinding.tvVaBindDriver.setText(DefaultUtil.getString(entity.getDriverName(), "无"));
            mBinding.tvVaBindDriverTeam.setText(DefaultUtil.getString(entity.getMotorcadeName(), "/"));
            if (TextUtils.isEmpty(entity.getDriverName())) {
                mBinding.tvVaBindDriverUnbind.setVisibility(View.GONE);
                mBinding.tvVaBindDriverJump.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvVaBindDriverUnbind.setVisibility(View.VISIBLE);
                mBinding.tvVaBindDriverJump.setVisibility(View.GONE);
            }
            //运输证信息
            if (TextUtils.isEmpty(entity.getTransportCertificateNum()) && TextUtils.isEmpty(entity.getTransportCertificateMain())) {
                mBinding.clVaTransport.setVisibility(View.GONE);
            } else {
                mBinding.clVaTransport.setVisibility(View.VISIBLE);
                //运输证信息
                if (TextUtils.isEmpty(entity.getTransportCertificateNum())) {
                    mBinding.groupVaTransportNumber.setVisibility(View.GONE);
                } else {
                    mBinding.groupVaTransportNumber.setVisibility(View.VISIBLE);
                    mBinding.tvVaTransportNumber.setText(DefaultUtil.getString(entity.getTransportCertificateNum()));
                }
                if (TextUtils.isEmpty(entity.getTransportCertificateMain())) {
                    mBinding.groupVaTransport.setVisibility(View.GONE);
                } else {
                    mBinding.groupVaTransport.setVisibility(View.VISIBLE);
                    loadImage(mBinding.ivVaTransport, entity.getTransportCertificateMain());
                    mImageUrls.add(DefaultUtil.getString(entity.getTransportCertificateMain()));
                }
            }
            if (TextUtils.isEmpty(entity.getImageApprovedLoadingQuality())) {
                mBinding.tvCarApprovedLoadMass.setVisibility(View.GONE);
            } else {
                mBinding.tvCarApprovedLoadMass.setVisibility(View.VISIBLE);
                mBinding.tvCarApprovedLoadMassText.setText(NumberUtil.trim0(entity.getImageApprovedLoadingQuality()) + "kg");
            }
            if (TextUtils.isEmpty(entity.getImageSizeL())) {
                mBinding.tvCarOverallDimension.setVisibility(View.GONE);
            } else {
                mBinding.tvCarOverallDimension.setVisibility(View.VISIBLE);
                mBinding.tvCarOverallDimensionText.setText(NumberUtil.trim0(NumberUtil.convertToDouble(entity.getImageSizeL())) + "mm");
            }
            if (TextUtils.isEmpty(entity.getImageVehicleAddress())) {
                mBinding.tvCarAddress.setVisibility(View.GONE);
            } else {
                mBinding.tvCarAddress.setVisibility(View.VISIBLE);
                if ((entity.getImageVehicleAddress().contains("省") && entity.getImageVehicleAddress().contains("市"))) {
                    mBinding.tvCarAddressText.setText(entity.getImageVehicleAddress());
                } else {
                    if (TextUtils.isEmpty(entity.getImageVehicleProvince()) || entity.getImageVehicleAddress().contains(entity.getImageVehicleProvince()) && TextUtils.isEmpty(entity.getImageVehicleCity()) || entity.getImageVehicleAddress().contains(entity.getImageVehicleCity())) {
                        mBinding.tvCarAddressText.setText(entity.getImageVehicleAddress());
                    } else {
                        mBinding.tvCarAddressText.setText(String.format("%s%s%s%s",
                                entity.getImageVehicleProvince(),
                                entity.getImageVehicleCity(),
                                entity.getImageVehicleDistrict(),
                                entity.getImageVehicleAddress()));
                    }
                }
            }
            if (TextUtils.isEmpty(entity.getImageNumber())) {
                mBinding.tvCarFileNumber.setVisibility(View.GONE);
            } else {
                mBinding.tvCarFileNumber.setVisibility(View.VISIBLE);
                mBinding.tvCarFileNumberText.setText(entity.getImageNumber());
            }

            mBinding.tvCarCharge.setText(TextUtils.isEmpty(entity.getLinkman()) ? "/" : entity.getLinkman());
            mBinding.tvCarChargePhone.setText(TextUtils.isEmpty(entity.getLinkmanPhone()) ? "/" : entity.getLinkmanPhone());

        } catch (Exception e) {
            mBinding.scrollVa.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(LogisticsEvent event) {
        //车辆编辑/完善信息/绑定/解绑司机回调
        if (event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT
                || event.getMessageTag() == EventConstant.EVENT_BIND_DRIVER
                || event.getMessageTag() == EventConstant.EVENT_UNBIND_DRIVER) {
            mViewModel.getVehicleDetail(mNo);
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.include.ivBack) {
            finish();
        } else if (v == mBinding.ivVaMain) {
            if (mEntity != null) {
                showImage(mEntity.getVehicleLicense());
            }
        } else if (v == mBinding.ivVaSub) {
            if (mEntity != null) {
                showImage(mEntity.getDrivingLicensePage());
            }
        } else if (v == mBinding.ivVaActual) {
            if (mEntity != null) {
                showImage(mEntity.getCarImage());
            }
        } else if (v == mBinding.ivVaTransport) {
            if (mEntity != null) {
                showImage(mEntity.getTransportCertificateMain());
            }
        } else if (v == mBinding.tvVaDrivingEdit) {
            //编辑驾照
            AddSelfCarActivity.start(this, mNo);
        } else if (v == mBinding.tvVaInfoEdit || v == mBinding.tvVaFixInfo) {
            //完善信息
            SelfCarInfoActivity.start(this, mNo);
        } else if (v == mBinding.tvVaBindRecord) {
            //绑定记录
            DriverBindRecordActivity.start(this, mNo);
        } else if (v == mBinding.tvVaBindDriverJump) {
            //绑定司机
            if (mEntity != null) {
                DriverBindActivity.start(this, NumberUtil.convertToLong(mEntity.getMotorcadeDriverNo()));
            }
        } else if (v == mBinding.tvVaBindDriverUnbind) {
            //解绑司机
            if (mEntity != null) {
                mViewModel.checkOrder(this, mEntity.getDriverNo(), mEntity.getNo());
            }
        }
    }

    /**
     * 点击展示大图
     */
    private void showImage(String imageUrl) {
        if (TextUtils.isEmpty(imageUrl) || ArrayUtil.isNullOrEmpty(mImageUrls)) {
            return;
        }
        int index = mImageUrls.indexOf(imageUrl);
        if (index == -1) {
            return;
        }
        ActivityJump.showBigPicture(this, mImageUrls, index);
    }

    private void showUnbindErrorDialog() {
        new RoundDialog.Builder(this)
                .title("提示")
                .content("当前车辆还有进行中的订单，不可解绑")
                .contentGravity(Gravity.CENTER)
                .show();
    }

    private void showUnbindDialog() {
        if (mEntity == null) return;
        new RoundDialog.Builder(this)
                .title("解绑司机")
                .content(String.format("确定要解除车辆（%s）与司机（%s）的绑定关系吗？"
                        , mEntity.getCarNumber()
                        , mEntity.getDriverName()))
                .contentGravity(Gravity.CENTER)
                .confirmCallback(v -> {
                    //调用解绑接口
                    mViewModel.unbindDriver(this, mEntity.getMotorcadeDriverNo());
                })
                .show();
    }

    private void loadImage(ImageView imageView, String url) {
        Glide.with(this).load(url)
                .apply(new RequestOptions().centerCrop())
                .placeholder(R.drawable.car_info_bg_img)
                .error(R.drawable.car_info_bg_img)
                .into(imageView);
    }
}
